defmodule ShortEner.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false

  use Application

  require Logger
  alias Logger, as: LOG

  def start(_type, _args) do
    prepare_mnesia()

    children = [
      # Starts a worker by calling: ShortEner.Worker.start_link(arg)
      # {ShortEner.Worker, arg}
      DbSupport.Mnesia.Repo,
      {DbSupport.Monitor.Mnesia, %{}},

      {Plug.Cowboy, 
        scheme: :http, 
        plug: ShortEner.Router, 
        options: [port: cowboy_port()]}
    ]

    LOG.info("running ShortEner...at #{cowboy_port()}")
    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: ShortEner.Supervisor]
    Supervisor.start_link(children, opts)
  end


  defp cowboy_port do
    Application.get_env(:short_ener, :cowboy_port, 9080)
  end

  defp prepare_mnesia do
    db_path = Application.get_env(:mnesia, :dir)
    LOG.debug("will init. in #{db_path}")
    master_node = System.get_env("MASTER_NODE", "")
    provider_impl = Application.get_env(:short_ener, :data_provider)

    if master_node == "" do
      LOG.debug("only master init.")
      provider_impl.init_master()
    else
      String.to_atom(master_node)
      |> provider_impl.add_self_to_cluster
    end
  end

end
